package com.seeyon.apps.thirdapp.mssage;

import com.alibaba.fastjson.JSON;
import com.seeyon.apps.thirdapp.constants.Constants;
import com.seeyon.apps.thirdapp.domain.MessageJSON;
import com.seeyon.apps.thirdapp.domain.MsgData;
import com.seeyon.apps.thirdapp.domain.Oacard;
import com.seeyon.apps.thirdapp.util.LanxinUtil;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.usermessage.pipeline.Message;
import com.seeyon.ctp.common.usermessage.pipeline.MessagePipeline;
import com.seeyon.ctp.util.Base64;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.LightWeightEncoder;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 蓝信消息通道
 * @author
 */
public class ThirdAppMessagePipeline implements MessagePipeline {

    private static final Log log = LogFactory.getLog(ThirdAppMessagePipeline.class);

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void invoke(Message[] messages) {
        List<Message>[] splitList = Strings.splitList(Arrays.asList(messages), 1000);
        for(List<Message> list : splitList) {
            for(Message message : list) {
                try{
                	/**项目：矿产资源【功能：过滤掉修改新闻、修改正文发送的消息提示】作者：tangqingtian 日期：2022年12月17日 start**/
                	//新闻模块
                	if(message.getCategory()==ApplicationCategoryEnum.news.key() && message.getContent().contains("修改了新闻")) {
                		log.info("--新闻修改不做蓝信消息推送！ " + JSON.toJSONString(message));
                		continue;
                	}
                	//修改正文
                	if(message.getCategory()==ApplicationCategoryEnum.edoc.key() && message.getContent().contains("修改公文")) {
                		log.info("--正文修改不做蓝信消息推送！ " + JSON.toJSONString(message));
                		continue;
                	}
                	/**项目：矿产资源【功能：过滤掉修改新闻、修改正文发送的消息提示】作者：tangqingtian 日期：2022年12月17日 end**/
                    log.info("客开，蓝信【消息】放消息的时间： " + JSON.toJSONString(message));
                    //将协同的消息给蓝信发过去
                    long startTime = System.currentTimeMillis();
                    MessageJSON messageObj = null;
                    Oacard oacard = null ;
                    MsgData msgData = null;
                    String app_token = null;

                    //app_token
                    app_token = LanxinUtil.getLxAccessToken("MSGTOKEN", true,true).getToken();
                    log.info("蓝信【oa_card_msg】app_token：" +app_token );
                    //接收者对应账号staffid

                    String receiverTelNumber = message.getReceiverMember().getTelNumber();
                    log.info("蓝信【oa_card_msg】receiverTelNumber：" +receiverTelNumber );
                    String receiverStaffid = LanxinUtil.getLxReceiver(app_token,receiverTelNumber);
                    log.info("蓝信【oa_card_msg】receiverStaffid：" +receiverStaffid);
                    //发送者staffid
                    String sendStaffid = message.getSenderMember().getCode();

                    //本地做测试注释
                    Date msgDate = message.getCreateDate();
                    String msfDateStr = Datetimes.formatDatetime(msgDate);

                    //判断协同消息必须为协同消息和公告消息 才推送蓝信
                    String[] urlAndSubject = getUrlAndSubject(message);
                    if(urlAndSubject != null) {
                        messageObj = new MessageJSON();
                        oacard = new Oacard();
                        msgData = new MsgData();
                        msgData.setOacard(oacard);
                        oacard.setTitle(urlAndSubject[0]);
                        oacard.setLink(urlAndSubject[1]);

                        //2022-07-26 王巧明 · PC蓝信消息穿透地址添加
                        oacard.setPcLink(urlAndSubject[2]);

                        //本地做测试注释
                        oacard.setSubTitle(msfDateStr);
                        if (sendStaffid !=null && !"".equals(sendStaffid)) {
                            oacard.setStaffId(sendStaffid);
                        }

                        messageObj.setMsgType("oacard");
                        messageObj.setMsgData(msgData);

                    }
                    //判断当前线程封装的实体类不为空
                    if (receiverStaffid !=null && !"".equals(receiverStaffid)) {
                        List reciveList = new ArrayList();
                        reciveList.add(receiverStaffid);
                        messageObj.setUserIdList(reciveList);
                    }

                    //消息推送  屏蔽没有地址的消息推送

                    if(urlAndSubject[1] !=null && !"".equals(urlAndSubject[1]) ){
                        //23-12-20 屏蔽底表移动端打不开消息，消息内容：您的工资已发放，请及时通过中矿OA-人力资源-工资管理模块查看详情
                        boolean contains = message.getContent().contains("您的工资已发放，请及时通过中矿OA-人力资源-工资管理模块查看详情");
                        if(contains){
                            messageObj.getMsgData().getOacard().setLink(null);
                        }
                         LanxinUtil.sendLxMessage(app_token, messageObj);
                     }

                    long endTime = System.currentTimeMillis();
                    log.info("蓝信【oa_card_msg】 执行共计花费时间： " +(endTime - startTime) + " ms");

                } catch (Exception e) {
                    log.error("蓝信消息发送出现异常，异常信息："  +e );
                }
            }
        }

    }

    /**
     * 获取需要穿透的URL 和消息的主题
     * @param message
     * @return
     */
    private String[] getUrlAndSubject(Message message) {
        String remoteUrl = message.getRemoteURL();
        String content = message.getContent();
        String linkType = message.getLinkType();
        log.info("消息结构"+message.toString());
        log.info("消息类型"+message.getCategory());
        log.info("消息地址"+remoteUrl);
        log.info("消息内容"+content);
        log.info("消息linkType"+linkType);

        // 过滤表单触发消息
        if("message.link.formtrigger.msg.flow".equals(linkType) || "message.link.formtrigger.msg.unflow".equals(linkType)) {
            return null;
        }
        //获取接收者的登录名
        String loginNane = message.getReceiverMember().getLoginName();

        byte[] bytes = loginNane.getBytes();
        byte[] baseBytes = Base64.encodeBase64(bytes, false);
        String ticket = new String(baseBytes);
        if(ticket.contains("=")) {
            ticket = ticket.replace("=", "@");
        }

        String authenticationFreeParameters ="L="+loginNane+"&U="+message.getReceiverMember().getId()+"&M=";
//        String authenticationFreeParameters = Base64Util.encode(loginNane+"-_-"+ UUIDUtil.getAbsUUIDLong());
        //2022-07-26 王巧明 · PC蓝信消息穿透地址
        String blueLetterPcRemoteUrl = "";

        //关联id， 即是需要穿透到指定页面的id
        Long id = message.getReferenceId();
        if(id == -1) {
            id = Long.valueOf(message.getLinkParams()[0]);
        }
        if(message.getCategory() == ApplicationCategoryEnum.collaboration.key()) {
            String path = "";
            if("message.link.col.supervise".equals(linkType) || "message.link.col.traceRecord".equals(linkType)) {// 判断是否督办消息或者流程表单触发的消息，进行屏蔽
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                path = "/seeyon/m3/apps/v5/collaboration/html/details/summary.html?affairId=" + id + "&openFrom=listPending&summaryId=-1&proxyId=0";
                remoteUrl = dealWithUrl(path, ticket);
                //pc : /seeyon/collaboration/collaboration.do?method=summary&openFrom=listDone&affairId=1866283123661423765&dumpData=undefined
                blueLetterPcRemoteUrl="/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId="+id+"&dumpData=undefined";

            }
        } else if(message.getCategory() == ApplicationCategoryEnum.meeting.key()) {
            String path = "/seeyon/m3/apps/v5/meeting/html/meetingDetail.html?meetingId=" + id + "&openFrom=pending&affairId=-1&proxyId=0&proxy=false";
            if("message.link.mt.room_perm".equals(linkType) || "message.link.office.meetingroom".equals(linkType) || "message.link.mt.summary".equals(linkType) || "message.link.mt.summary_send".equals(linkType)) {
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                remoteUrl = dealWithUrl(path, ticket);
                //pc : /seeyon/meeting.do?method=view&meetingId=7710164476036268053
                blueLetterPcRemoteUrl="/meeting.do?method=view&meetingId="+id;

            }
        } else if(message.getCategory() == ApplicationCategoryEnum.bulletin.key()) {// 公告
            String path = "/seeyon/m3/apps/v5/bulletin/html/bulView.html?bulId=" + id + "&comeFrom=0";
            if("message.link.bul.auditing".equals(linkType) || "message.link.bul.writedetail".equals(linkType)) {
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                remoteUrl = dealWithUrl(path, ticket);
                //pc : /seeyon/bulData.do?method=bulView&bulId=-1901335380712339846&from=message&_isModalDialog=true
                blueLetterPcRemoteUrl="/bulData.do?method=bulView&bulId="+id+"&from=message&_isModalDialog=true";

            }
        } else if(message.getCategory() == ApplicationCategoryEnum.news.key()) {// 新闻
            String path = "/seeyon/m3/apps/v5/news/html/newsView.html?newsId=" + id + "&comeFrom=0";
            if("message.link.news.auditing".equals(linkType) || "message.link.news.writedetail".equals(linkType) || "message.link.news.alreadyauditing".equals(linkType)) {
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                remoteUrl = dealWithUrl(path, ticket);
                //pc :
                blueLetterPcRemoteUrl = "/newsData.do?method=newsView&newsId="+id+"&from=message&_isModalDialog=true";

            }
        } else if(message.getCategory() == ApplicationCategoryEnum.bbs.key()) {// 讨论
            String path = "/seeyon/m3/apps/v5/bbs/html/bbsView.html?bbsId=" + id + "&from=message";
            remoteUrl = dealWithUrl(path, ticket);
            //pc :
            blueLetterPcRemoteUrl = "/seeyon/bbs.do?method=bbsView&articleId="+id+"&from=message&_isModalDialog=true";


        } else if(message.getCategory() == ApplicationCategoryEnum.inquiry.key()) {// 调查
            String path = "/seeyon/m3/apps/v5/inquiry/html/inquiryView.html?inquiryId=" + id + "&comeFrom=0";
            if("message.link.inq.auditing".equals(linkType) || "message.link.inq.alreadyauditing.pass".equals(linkType) || "message.link.inq.alreadyauditing.nopass".equals(linkType)) {
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                remoteUrl = dealWithUrl(path, ticket);
                //pc :
                blueLetterPcRemoteUrl="/inquiryData.do?method=inquiryView&inquiryId="+id+"&from=message&_isModalDialog=true";

            }
        } else if(message.getCategory() == ApplicationCategoryEnum.edoc.key() || message.getCategory() == ApplicationCategoryEnum.edocSend.key() || message.getCategory() == ApplicationCategoryEnum.edocRec.key() || message.getCategory() == ApplicationCategoryEnum.edocSign.key() || message.getCategory() == ApplicationCategoryEnum.exSend.key() || message.getCategory() == ApplicationCategoryEnum.exSign.key() || message.getCategory() == ApplicationCategoryEnum.edocRegister.key() || message.getCategory() == ApplicationCategoryEnum.edocRecDistribute.key() || message.getCategory() == ApplicationCategoryEnum.exchange.key()) {
            String path = "";
            if(Strings.isBlank(linkType) || "message.link.edoc.supervise.detail".equals(linkType) || "message.link.edoc.supervise.main".equals(linkType) || "message.link.exchange.distribute".equals(linkType) || "message.link.exchange.receive".equals(linkType) || "message.link.exchange.register.govpending".equals(linkType) || "message.link.exchange.register.pending".equals(linkType) || "message.link.exchange.register.receive".equals(linkType) || "message.link.exchange.registered".equals(linkType) || "message.link.exchange.send".equals(linkType) || "message.link.exchange.sent".equals(linkType) || "message.link.edoc.traceRecord".equals(linkType)) {
                content = Strings.isBlank(content) ? "请登录内部协同系统进行处理，谢谢！" : content + "，请登录内部协同系统进行处理，谢谢！";
                remoteUrl = "";

            } else {
                //path = "/seeyon/m3/apps/v5/edoc/html/edocSummary.html?affairId=" + id + "&openFrom=listPending&summaryId=-1&proxyId=0";

                path = "/seeyon/m3/apps/v5/edoc/html/details/summary.html?affairId=" + id + "&openFrom=listPending&summaryId=-1&proxyId=0";

                remoteUrl = dealWithUrl(path, ticket);
                //pc :
                blueLetterPcRemoteUrl = "/govdoc/govdoc.do?method=summary&openFrom=listPending&affairId="+id+"&contentAnchor=&_isModalDialog=true";

            }
        }else{
            String path = "";


        }
        String[] result = new String[3];
        result[0] = content;
        result[1] = remoteUrl;
        result[2] = dealWithPCUrl(blueLetterPcRemoteUrl,authenticationFreeParameters);

        log.info(JSONUtil.toJSONString(result));
        return result;
    }

    @SuppressWarnings("deprecation")
    private static String dealWithUrl(String url, String ticket) {

        return Constants.SEEYON_MESSAGE_ACCESS_URL.replace("@ticket@", ticket).replace("@url@", URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_MESSAGE_INDEX_URL.replace("@html@", URLEncoder.encode(url + "&weixinMessage=true")))));
    }

    /**
     * 2022-07-26 王巧明 · PC蓝信消息穿透地址拼接
     */
    private static String dealWithPCUrl(String url, String authenticationFreeParameters) {
//        return  Constants.SEEYON_MESSAGE_ACCESS_PCURL.replace("@ticket@", authenticationFreeParameters).replace("@url@", URLEncoder.encode("/seeyon"+url));
        return Constants.SEEYON_PCPENETRATE_CONTROL_URL+"&enc="+LightWeightEncoder.encodeString(authenticationFreeParameters+URLEncoder.encode(url));
    }


    /**
     * @param args
     */

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Integer> getAllowSettingCategory(User arg0) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return "OA蓝信消息";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getShowName() {
        return "OA蓝信消息";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getSortId() {
        return 20;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String isAllowSetting(User arg0) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAvailability() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isDefaultSend() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isShowSetting() {
        return true;
    }

}
